<template>
  <div class="resident-detail-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <div class="blue-line"></div>
        <h2>居民详情</h2>
      </div>
      <el-button type="success" class="send-message-btn">发消息</el-button>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="resident-tabs">
      <!-- 健康档案 -->
      <el-tab-pane label="健康档案" name="health">
        <HealthProfile :resident-id="residentId" />
      </el-tab-pane>

      <!-- 签约信息 -->
      <el-tab-pane label="签约信息" name="contract">
        <ContractInfo :resident-id="residentId" v-if="activeTab === 'contract'" />
      </el-tab-pane>

      <!-- 服务记录 -->
      <el-tab-pane label="服务记录" name="service">
        <ServiceRecords :resident-id="residentId" v-if="activeTab === 'service'" />
      </el-tab-pane>
    </el-tabs>

    <!-- 底部按钮 -->
    <div class="footer-buttons">
      <el-button type="primary" @click="handleEdit" v-if="activeTab === 'health'" size="large">
        编辑档案信息
      </el-button>
      <el-button type="info" @click="showQrDialog" v-if="activeTab === 'health'" size="large">
        查看二维码
      </el-button>
      <el-button @click="handleBack" size="large">返回</el-button>
    </div>

    <el-dialog v-model="qrDialogVisible" title="居民二维码" width="350px" :close-on-click-modal="false">
      <div v-if="qrLoading" style="text-align:center;padding:30px 0;">
        <el-icon><Loading /></el-icon>
        正在生成二维码...
      </div>
      <div v-else-if="qrImgUrl" style="text-align:center;">
        <img :src="qrImgUrl" alt="二维码" style="max-width: 250px;max-height: 250px;" />
        <div style="margin-top:10px;color:#888;font-size:12px;">扫码可查看居民信息</div>
      </div>
      <div v-else style="text-align:center;color:red;">二维码生成失败</div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import HealthProfile from './components/HealthProfile.vue'
import ContractInfo from './components/ContractInfo.vue'
import ServiceRecords from './components/ServiceRecords.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const activeTab = ref('health')
const residentId = ref('')
const qrDialogVisible = ref(false)
const qrImgUrl = ref('')
const qrLoading = ref(false)

// 假设你有获取居民详细信息的API
const residentInfo = ref({})

// 方法
const handleEdit = () => {
  router.push({ name: 'ResidentInfo', query: { id: residentId.value } })
}

const handleBack = () => {
  router.go(-1)
}

const fetchResidentInfo = async () => {
  // 这里请根据你的实际API调整
  try {
    const resp = await axios.get(`/resident/getResidentDetail/${residentId.value}`)
    console.log('fetchResidentInfo resp.data:', resp.data)
    // 自动适配两种返回结构
    if (resp.data && resp.data.data) {
      residentInfo.value = resp.data.data
    } else {
      residentInfo.value = resp.data
    }
  } catch (e) {
    residentInfo.value = {}
  }
}

const showQrDialog = async () => {
  qrDialogVisible.value = true
  qrLoading.value = true
  qrImgUrl.value = ''
  // 先获取居民详情
  await fetchResidentInfo()
  console.log('residentInfo.value', residentInfo.value)
  if (!residentInfo.value || (!residentInfo.value.id && !residentInfo.value.name)) {
    qrLoading.value = false
    ElMessage.error('居民信息获取失败')
    return
  }
  // 请求后端生成居民信息图片，获取图片URL
  let imageUrl = ''
  try {
    const resp = await axios.get(`/resident/generateResidentInfoImage/${residentInfo.value.id}`)
    imageUrl = resp.data && resp.data.url ? resp.data.url : ''
  } catch (e) {
    imageUrl = ''
  }
  if (!imageUrl) {
    qrLoading.value = false
    ElMessage.error('居民信息图片生成失败')
    return
  }
  // 组装二维码内容（图片URL）
  let words = ''
  try {
    words = encodeURIComponent(imageUrl)
  } catch (e) {
    words = encodeURIComponent('二维码生成异常')
  }
  // 请求二维码API
  try {
    const params = `words=${words}&image_url=&is_gif=false`
    const { data } = await axios.post(
      'https://eolink.o.apispace.com/ercode/api/v1/forward/qr_code',
      params,
      {
        headers: {
          'X-APISpace-Token': 'jdpd8ho97wk26fkrwazojub0asd2euf0',
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      }
    )
    if (data && data.code === 200 && data.data && data.data.qr_path) {
      qrImgUrl.value = data.data.qr_path
    } else {
      qrImgUrl.value = ''
      ElMessage.error('二维码生成失败')
    }
  } catch (e) {
    qrImgUrl.value = ''
    ElMessage.error('二维码生成失败')
  } finally {
    qrLoading.value = false
  }
}

// 组件挂载时执行
onMounted(() => {
  residentId.value = route.query.id || route.params.id
  fetchResidentInfo()
})
</script>

<style scoped>
.resident-detail-container {
  width: 1400px;
  margin: 0 auto;
  padding: 20px;
  background: white;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.blue-line {
  width: 4px;
  height: 24px;
  background: #409EFF;
  margin-right: 8px;
}

.header-left h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.send-message-btn {
  background: #67C23A;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
}

.resident-tabs {
  background: rgba(242, 247, 251, 0.498039215686275);
  border-radius: 8px;
  padding: 0;
}

.resident-tabs ::v-deep .el-tabs__header {
  margin: 0;
  border-bottom: none;
  background: transparent;
}

.resident-tabs ::v-deep .el-tabs__active-bar {
  display: none;
}

.resident-tabs ::v-deep .el-tabs__nav-wrap {
  background: transparent;
  padding: 0 8px;
}

.resident-tabs ::v-deep .el-tabs__nav-wrap:after {
  display: none !important;
}

.resident-tabs ::v-deep .el-tabs__item {
  padding: 0 16px !important;
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  background: transparent;
  margin: 0 2px;
}

.resident-tabs ::v-deep .el-tabs__header .el-tabs__item:nth-child(2) {
  padding-left: 16px !important;
}

.resident-tabs ::v-deep .el-tabs__header .el-tabs__item:first-child {
  padding-left: 16px !important;
}

.resident-tabs ::v-deep .el-tabs__header .el-tabs__item:last-child {
  padding-right: 16px !important;
}

.resident-tabs ::v-deep .el-tabs__item.is-active {
  background: #409EFF;
  color: white;
  border-radius: 4px 4px 0 0;
}

.resident-tabs ::v-deep .el-tab-pane {
  padding: 20px;
  min-height: 500px;
  background: white;
  border-radius: 0 0 8px 8px;
}

.footer-buttons {
  margin-top: 20px;
  text-align: left;
}

.footer-buttons .el-button {
  margin-right: 10px;
}
</style>